package com.atstudy.ticket;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2022/12/23 9:48
 * @copyright: 博为峰
 */
public class Ticket03 implements Runnable {

    public static int num = 100;
    public static boolean flag = true;

    /*
       线程安全问题的原因：
       1.多个线程同时操作共享数据
       2.操作共享数据的代码有多行

       锁:
       同步代码块
       synchronized (任意对象) {
       }

       同步方法：锁对象 this
       静态同步方法：字节码文件对象
    */
    public Object obj = new Object();

    @Override
    public void run() {
        while (flag) {//还是最后一张票
            saleStatic();
        }
    }

    private static synchronized void saleStatic() {//静态同步方法, 锁: 当前字节码文件对象（.class）
        if (num > 0) {//t0  t1  t2   t3
            // 0  -1  -2  -3
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "," + num--);
        } else {
            flag = false;
        }
    }

    private synchronized void sale() {//同步方法, 锁当前对象this Ticket03 ticket03 = new Ticket03();
        if (num > 0) {//t0  t1  t2   t3
            // 0  -1  -2  -3
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "," + num--);
        } else {
            flag = false;
        }
    }

    public void run1() {
        while (flag) {//还是最后一张票
            synchronized (obj) {
                if (num > 0) {//t0  t1  t2   t3
                    // 0  -1  -2  -3
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "," + num--);
                } else {
                    flag = false;
                }
            }
        }
    }
}
